package com.wmuj.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wmuj.mapper.ClazzMapper;
import com.wmuj.mapper.ClazzStudentMapper;
import com.wmuj.pojo.*;
import com.wmuj.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
  /**
   * 班级管理条件查询
   *
   * @param clazzsQueryParam
   * @return
   */
  @Autowired private ClazzMapper clazzMapper;

  @Autowired private ClazzStudentMapper clazzStudentMapper;

  @Override
  public PageResult<Clazz> queryClazzsList(ClazzsQueryParam clazzsQueryParam) {
    PageHelper.startPage(clazzsQueryParam.getPage(), clazzsQueryParam.getPageSize());
    List<Clazz> rows = clazzMapper.list(clazzsQueryParam);
    Page<Clazz> p = (Page<Clazz>) rows;
    // 对rows里的status进行判断 当前时间<beginDate 显示 未开班 ，当前时间>endData 显示 已结课，否则就是在读中
    for (Clazz clazz : p.getResult()) {
      if (clazz.getBeginDate().isAfter(LocalDate.now())) {
        clazz.setStatus("未开班");
      } else if (clazz.getEndDate().isBefore(LocalDate.now())) {
        clazz.setStatus("已结课");
      } else {
        clazz.setStatus("在读中");
      }
    }
    return new PageResult<Clazz>(p.getTotal(), p.getResult());
  }

  //  进行事务控制删除两个数据库的信息
  @Transactional
  @Override
  public void delete(Integer id) {
    // 1.根据id 删除班级的基本信息
    clazzMapper.delete(id);
    // 2.根据班级id删除班级对应的学生信息
    clazzStudentMapper.deleteStuIds(id);
  }

  @Override
  public void addInfo(Clazz clazz) {
    clazz.setCreateTime(LocalDateTime.now());
    clazz.setUpdateTime(LocalDateTime.now());
    clazzMapper.addInfo(clazz);
  }

  @Override
  public Clazz findById(Integer id) {
    return clazzMapper.findById(id);
  }

  @Override
  public void update(Clazz clazz) {
    clazz.setUpdateTime(LocalDateTime.now());
    clazzMapper.update(clazz);
  }

  @Override
  public Object findAllList() {
    List<Clazz> list = clazzMapper.findAllList();
    return list;
  }
}
